package com.ilxqx.framework.util;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author venus
 * Spring中bean和请求响应对象获取工具类
 */
public final class SpringUtils implements ApplicationContextAware {

    /**
     * spring应用上下文对象
     */
    private static ApplicationContext applicationContext;

    /**
     * 设置spring应用上下文对象函数
     * @param applicationContext 应用上下文对象
     * @throws BeansException Bean异常
     */
    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 获取Bean对象
     * @param cls Bean类
     * @param <T> 泛型
     * @return bean对象
     */
    public static <T> T getBean (Class<T> cls) {
        return applicationContext.getBean(cls);
    }

    /**
     * 获取Bean对象
     * @param name bean名称
     * @param <T> 泛型
     * @return bean对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean (String name) {
        var bean = applicationContext.getBean(name);
        return (T) bean;
    }

    /**
     * 获取Bean对象
     * @param name bean名称
     * @param cls Bean类
     * @param <T> 泛型
     * @return bean对象
     */
    public static <T> T getBean (String name, Class<T> cls) {
        return applicationContext.getBean(name, cls);
    }

    /**
     * 获取request对象
     * @return request对象
     */
    public static HttpServletRequest getRequest () {
        var servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            return null;
        }
        return servletRequestAttributes.getRequest();
    }

    /**
     * 获取response对象
     * @return response对象
     */
    public static HttpServletResponse getResponse () {
        var servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            return null;
        }
        return servletRequestAttributes.getResponse();
    }

}